# -*- utf-8 -*-

import requests
import json
import re
from time import sleep
from bs4 import BeautifulSoup
import time
import datetime
from requests.adapters import HTTPAdapter
from time import strftime, localtime


def unicode_to_cn(in_str, debug=False):
    out = None

    if isinstance(in_str, bytes):
        temp = str(in_str, encoding='utf-8')
        out = temp.encode('utf-8').decode('unicode_escape')
    else:
        out = in_str.encode('utf-8').decode('unicode_escape')

    return out



def baojing(wenben):
    dingding = '钉钉报警接口'

    headers = {
        'Content-Type': 'application/json'
    }
    aaa = {"msgtype": "text",
            "text": {
                "content": wenben
            }}
    resp = requests.post(url=dingding, headers=headers, json=aaa)
    print(resp)

def get_bs(link):
    headers = {
        'Host': 'api2.xfb315.com',
        'Connection': 'keep-alive',
        'Content-Length': '743',
        'Accept': 'application/json, text/plain, */*',
        'Origin': 'https://www.xfb315.com',
        'Accept-Language': 'zh-CN,zh;q=0.8',
        'source': 'pc',
        'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.70 Safari/537.36',
        'Content-Type': 'application/x-www-form-urlencoded',
        'Sec-Fetch-Site': 'same-site',
        'Sec-Fetch-Mode': 'cors',
        'Referer': 'https://www.xfb315.com/search/all?searchKey=%E7%9F%B3%E5%8A%9B%E6%B4%BE',
        'Accept-Encoding': 'gzip, deflate'

    }
    params = {'code': 'rcFnU51StKgJ/e9rx63uh7fELu5cJIgs5PLnm32nvcfk6Ry0VWITmG5JPH+5WytqwQz5cjzRB9eoIkJKEUAK6'
                    '/u2ceD3OZxg8dDWnxymUyHdbJAY4FFdoQkZorqOFv'
                    '/z7aEBqFKyzGRRP7fM0sRQGWoKPnnVlMVXgnrdJw8qpHxYFJJPcvPF4UHHVSQuNCqI/nTUQm'
                    '+yXhxzkBPUiMMsF7fSdKyGnFO0dIujM8nMJiJdVFb8qaq'
                    '+W4gYAWvhEKYI8k1uXvlJ1kh6b6iKT5pTGvwjlZC5F3NKEnG3zD6HlvDq2tjzSQ7vsmfoq'
                    '/gMILi9nxx8ZQKGOArCyL5leQb2oQ7mLksTRFt1qR2GUWXNKZe'
                    '+zzAAs1VRysBBGzOp5N9RYfFrfnWQxAxJgmJAPm19pbCCrJVl+wiImsZQbLz9iajbpLAZD1bIQncNi8Ir2vvuucEMOtzl4'
                    '/YFPFLZTV5djp/7fROHj1d7sIWvL46JeNkyNR7yS/p3mx5se'
                    '/X23IE7RCte13ENEo1dEbvdnyFX4xc1LbHrEtM8NeQOJv60W5ULB8IPkdYpFjUJarA/XfnxEmV+/E+3rslni'
                    '/r7NN7FkpAtE60/OeypTlxija2eoeNW/mQQjT0LFkJOWzwrE+UsGCNFN3eusjfJTGC+DNOJK/t3ALdZpoFv9Z8+QNMI/Mw='}
    s = requests.Session()
    s.mount('http://', HTTPAdapter(max_retries=3))  # 设置重试次数为3次
    s.mount('https://', HTTPAdapter(max_retries=3))
    response = s.post(link, data=params, headers=headers, timeout=150)
    ttt = response.text

    f1 = open('已报警内容.txt', 'r+', encoding='utf-8')
    list1 = f1.readlines() #readlines获得的直接就是列表了

    if 'h_title' not in ttt:
        print('没有找到结果')
    else:

        print('=========仅展示最近的一条投诉，详情请查看链接==========')
        title = ttt.split('h_title":"')[1].split('","')[0]
        # title1 = re.sub('<(S*?)[^>]*>.*?|<.*? />', '', title)
        title2 = unicode_to_cn(title)
        print('标题：' + title2)
        # 
        summary = ttt.split('content":"')[1].split('","')[0]   #
        # summary1 = re.sub('<(S*?)[^>]*>.*?|<.*? />', '', summary)
        summary2 = unicode_to_cn(summary)
        print('投诉内容：' + summary2)
        #
        # 
        print('https://www.xfb315.com/search/all?searchKey=%E7%9F%B3%E5%8A%9B%E6%B4%BE')
        # 
        summary2_1 = summary2 + '\n' #投诉内容加换行，用来判断是否已报警过
        if summary2_1 in list1:
            print('已经报警过了')
        else:
            summary3 = summary2 + ':' + 'https://www.xfb315.com/search/all?searchKey=%E7%9F%B3%E5%8A%9B%E6%B4%BE'
            baojing(summary3)
            f1.writelines(summary2_1)
    f1.close()



#f = open('已报警内容.txt', 'w', encoding='utf-8')

while 1:
    url = 'https://api2.xfb315.com/v6.5.1/search'
    try:
        page = get_bs(url)
        print('315消费宝平台监控完毕...30分钟后进行下一轮扫描'+'\n')
        print(strftime('%Y-%m-%d %H:%M:%S', localtime()))
        time.sleep(1800)
    except Exception as e:
        print(e)
        time.sleep(7200)

    continue


